﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DalatCooking.Core;
using DalatCooking.Core.Helper;
public partial class Widgets_Poll : System.Web.UI.UserControl
{
    public int PollID { get; set; }
    public int ModuleID { get; set; }
    public string Name { get; set; }
    public string Title { get; set; }
    public string Params { get; set; }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        if (!IsPostBack)
        {
            Module m = ModuleManager.FindById(ModuleID);
            if (m != null)
            {
                PollID = ConvertObject.ToInt(m.Params);

                divMsg.Visible = false;

                if (PollID > 0)
                    hidPollID.Value = PollID.ToString();

                else
                {
                    divMsg.InnerHtml = "<b>Thông tin: </b>Chưa có bình chọn.";
                    divPoll.Visible = false;
                    divMsg.Visible = true;
                    return;
                }

                showPoll();//show the poll              
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
       
    }
   
    
    private void showPoll()
    {

        DataSet dsPoll = PollManager.FindPoll_ByID(PollID);

        if (dsPoll.Tables[0].Rows.Count > 0)
        {
            litQuestion.Text = dsPoll.Tables[0].Rows[0]["Question"].ToString();

            //if the BlockMode is not NONE findout whether the user is already Polled or not - if polled show the result only
            string blockMode = dsPoll.Tables[0].Rows[0]["BlockMode"].ToString();

            bool isPolled = CheckAlreadyPolled(blockMode);

            if (isPolled) //show the result
            {
                divAnswers.InnerHtml = getResultHTML(dsPoll);
                divAnswers.InnerHtml += "<div class='poll-total' id='divVoted'>Bạn đã bình chọn rồi.</div>";
            }
            else //show the poll
            {
                rptChoices.DataSource = dsPoll.Tables[1];
                rptChoices.DataBind();
                rptChoices.Visible = rptChoices.Items.Count > 0;
            }
        }
        else
        {
            divMsg.InnerHtml = "<b>Thông tin: </b> Chưa có bình chọn.";
            divMsg.Visible = true;
        }
    }

    private bool CheckAlreadyPolled(string blockMode)
    {
        bool isPolled = false;
        //if the block mode of this Poll is by IP,, check in the DB whether a poll is already existing from this IP
        if (blockMode == "IP_ADDRESS")
        {
            string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            int id = PollManager.SelectPollIP(int.Parse(hidPollID.Value), ip);
            if (id > 0) isPolled = true;
        }
        else if (blockMode == "COOKIE") //If block by Cookie read the cookie to see if there is an entry for this blog
        {
            if (Request.Cookies["Poll"] != null && Request.Cookies["Poll"]["ID"] != null)
            {
                //the cookie will have comma seperated IDs of all the polls that already voted
                string commaSeperatedPollIDs = Request.Cookies["Poll"]["ID"];
                //split it with comma
                string[] pollIDs = commaSeperatedPollIDs.Split(",".ToCharArray());
                //and loop through each pollID to find whethere the current poll is already voted
                foreach (string pID in pollIDs)
                {
                    //if yes break
                    if (pID == hidPollID.Value)
                    {
                        isPolled = true;
                        break;
                    }
                }
            }
        }

        return isPolled;
    }
    private static string getResultHTML(DataSet dsPoll)
    {
        int totalVotes = int.Parse(dsPoll.Tables[1].Compute("Sum(VoteCount)", String.Empty).ToString());
        System.Text.StringBuilder sbResult = new System.Text.StringBuilder();
        sbResult.Append("<ul>");
        foreach (DataRow dr in dsPoll.Tables[1].Rows)
        {
            decimal percentage = 0;
            if (totalVotes > 0)
                percentage = decimal.Round((decimal.Parse(dr["VoteCount"].ToString()) / decimal.Parse(totalVotes.ToString())) * 100, MidpointRounding.AwayFromZero);

            string alt = dr["VoteCount"].ToString() + " votes out of " + totalVotes.ToString();
            sbResult.Append("<li>");
            sbResult.Append("<label class='poll-result'>").Append(dr["Choice"]).Append(" (").Append(dr["VoteCount"]).Append(" bình chọn - ").Append(percentage).Append("%)</label>");
            sbResult.Append("<div class='poll-chart'><img src='/images/red-bar.png' width='0%' val='").Append(percentage).Append("%' height='15px' alt='").Append(alt).Append("' title='").Append(alt).Append("' /> ").Append("</div>");
            sbResult.Append("</li>");
        }
        sbResult.Append("</ul>");
        sbResult.Append("<div class='poll-total''>Tổng cộng: ").Append(totalVotes).Append(" lượt bình chọn.</div>");
        //sbResult.Append("</p>");
        return sbResult.ToString();
    }
}